<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of BAppUI
 *
 * @author ID59C
 */
class BUIBlyn extends BUINode {

    const LEFTMENU = "leftmenu";
    const MAINMENU = 'mainmenu';
    const Menu_WorkingSpacesLinks = "workingSpacesLinks";
    const Menu_FollowingSpacesLinks = "followingSpacesLinks";
    const Theme_PC_Bootstrap = 'pc_bootstrap';
    const Theme_JMQuery_Wechat = 'jqm_wechat';
    const Theme_Tablet_Bootstrap = 't_bootstrap';
    const Theme_Mobile_Bootstrap = 'mb_bootstrap';
    const Theme_Admin_Bootstrap = 'a_bootstrap';
    const Theme_Mobile_Angular = 'mb_angular';
    const Theme_PC_Angular = 'pc_angular';
    const DEVICE_IPHONE = 'iphone';
    const DEVICE_IPAD = "ipad";
    const DEVICE_ANDROID_TABLET = 'android_tablet';
    const DEVICE_MOBILE_GENERAL = "mobile_general";
    const DEVICE_TABLET_GENERAL = "tablet_general";
    const DEVICE_ANDROID = 'android';
    const HomeNode_PersonalSpace = 'home_node_personal_Space';
    const View_Container_Id = 'blyn_container';
    const View_Layout_Id = 'blyn_layout';
    const View_TopBar_Id = 'bly_topBar';

    //protected $theme = null;
    protected $startScreen = null;
    protected $startScreenFlow = null;
    protected $layoutView = null;
    protected $views = array();
    private $mySpaceLinkBeforeSend = null;
    private $mySpacesLinkBeforeSend = null;
    public $menus = array();
    private $links = array();
    public $startView = array();
    //private $exitGoto = false;
    public $gotoNode = FALSE;
    public $updateControl = null;
    public $senderControl = null;
    protected $activeLink = null;
    protected $linkData = array();
    protected $currentScreen = null;

    public function __construct($node = NULL) {
        parent::__construct($node);

        $basePath = 'application.application';
        $this->uiPath = $basePath . '.ui';

        $uiPath = $this->uiPath;

        //$uiPath = $node->uiPath;

        if ($this->modelPath == NULL)
            $this->modelPath = $uiPath . '.models';

        if ($this->screenPath == NULL)
            $this->screenPath = $uiPath . '.screens';

        if ($this->screenflowPath == NULL)
            $this->screenflowPath = $uiPath . '.screenflows';

        if ($this->widgetPath == NULL)
            $this->widgetPath = $uiPath . '.widgets';

        if ($this->uiControlPath == NULL)
            $this->uiControlPath = $uiPath . '.controls';

        yii::import($this->modelPath . '.*');
        yii::import($this->screenPath . '.*');
        yii::import($this->widgetPath . '.*');
        yii::import($this->uiControlPath . '.*');

        if ($this->theme == NULL)
            $this->setTheme(self::Theme_PC_Bootstrap);

        //$paths = $node->getConfig()->getConfig('paths.basePath');
        //$uiPath = $paths['uiPath'];

        if ($this->viewPath == NULL)
            $this->viewPath = $uiPath . ".themes." . $this->getTheme() . '.views';

        if ($this->formPath == NULL)
            $this->formPath = $uiPath . ".themes." . $this->getTheme() . '.forms';
    }

    public function setTheme($theme) {
        parent::setTheme($theme);
        $this->viewPath = $this->uiPath . ".themes." . $this->getTheme() . '.views';
        $this->formPath = $this->uiPath . ".themes." . $this->getTheme() . '.forms';
    }

    public function getViewPath($data = NULL) {
        return $this->uiPath . ".themes." . $this->getTheme() . '.views';
    }

    public function getName() {
        return 'blyn';
    }

    public function oldrenderLogin() {
        $controller = Yii::app()->getController();

        $form = $this->getFormByMeta("Login");
        $signForm = $this->getFormByMeta("Signup");

        $loginModel = null;
        $controller->renderLogin = true;
        $loginStatus = BUserIdentity::ERROR_NONE;

        if ($form->submitted("login")/* && $form->validate() */) {
            if ($form->validate()) {
                $loginModel = $form->getModel();
//                if ($loginModel->login()) {
//                    $this->setContext();
//                    Blyn::app()->runApp();
//                }
                $loginStatus = $loginModel->login();
                if ($loginStatus < 0) {
                    $controller->layout = "//layouts/column1";
                    $controller->render("registerNotice", array('email' => $loginModel->email));
                    Blyn::app()->end();
                } else if ($loginStatus == BUserIdentity::ERROR_NONE) {
                    $this->setContext();
                    Blyn::app()->runApp();
                }
            }
        }

        if ($form->submitted("signup")) {
            //  $controller->redirect(array("site/signup"));
            $controller->renderLogin = FALSE;
            $controller->layout = "//layouts/column1_1";
            $controller->render("showOneForm", array('form' => $signForm, 'loginStatus' => $loginStatus));
        }

        if ($signForm->submitted("signup")) {
            $controller->renderLogin = FALSE;
            if ($signForm->validate()) {
                $model = $signForm->getModel();
                if ($model->signUp()) {
                    $loginModel = new LoginFormModel();
                    $loginStatus = $loginModel->login($model->email, $model->password);
                    if ($loginStatus < 0) {
                        $controller->layout = "//layouts/column1";
                        $controller->render("registerMail", array('email' => $model->email));
                        Blyn::app()->end();
                    } else if ($loginStatus == BUserIdentity::ERROR_NONE) {
                        $this->setContext();
                        Blyn::app()->runApp();
                    }
                }
            }
            $controller->layout = "//layouts/column1_1";
            $controller->render("showOneForm", array('form' => $signForm, 'loginStatus' => $loginStatus));
        }

        if ($controller->renderLogin) {
            $controller->layout = "//layouts/column1_1";
            $controller->render('login', array('form' => $form, 'loginStatus' => $loginStatus));
        }
    }

    public function renderLogin() {
        $controller = Yii::app()->getController();

        $loginForm = $this->getFormByMeta("Login");
        $loginModel = $loginForm->getModel();
        $controller->renderLogin = true;
        $loginStatus = BUserIdentity::ERROR_NONE;

        if (isset($_POST['LoginFormModel'])) {
            $loginModel->attributes = $_POST['LoginFormModel'];
            if ($loginForm->validate()) {
                $loginStatus = $loginModel->login();
                if ($loginStatus < 0) {
                    $controller->layout = "//layouts/column1";
                    $controller->render("registerNotice", array('email' => $loginModel->email));
                    Blyn::app()->end();
                } else if ($loginStatus == BUserIdentity::ERROR_NONE) {
                    $this->setContext();
                    Blyn::app()->runApp();
                } else {
                    $controller->render('login', array('form' => $loginForm, 'model' => $loginModel,
//                        'registerForm' => $signUpForm, 'registerModel' => $signUpModel,
                        'loginStatus' => $loginStatus,));
                }
            } else {
                $loginStatus = BUserIdentity::ERROR_USERNAME_INVALID;
                $controller->render('login', array('form' => $loginForm, 'model' => $loginModel,
                    'loginStatus' => $loginStatus,));
            }
        } else if ($controller->renderLogin) {
//            $controller->layout = "//layouts/main2";
            $controller->render('login', array('form' => $loginForm, 'model' => $loginModel,
                'loginStatus' => $loginStatus,));
        }
    }

    public function renderRegisterNewUser() {
        $controller = Yii::app()->getController();

//        $loginForm = $this->getFormByMeta("Login");
//        $loginModel = $loginForm->getModel();
        $signUpForm = $this->getFormByMeta("Signup");
        $signUpModel = $signUpForm->getModel();
        $controller->renderLogin = true;
        $loginStatus = BUserIdentity::ERROR_NONE;

        if (isset($_POST['SignupFormModel'])) {
            $signUpModel->attributes = $_POST['SignupFormModel'];
            if ($signUpForm->validate()) {
                $model = $signUpForm->getModel();
                if ($model->signUp()) {
                    $loginModel = new LoginFormModel();
                    $loginStatus = $loginModel->login($model->email, $model->password);
                    if ($loginStatus < 0) {
//                        $controller->layout = "//layouts/column1";
//                        $controller->render("registerMail", array('email' => $model->email));
//                        Blyn::app()->end();
                        // comment out register job: not finish yet.
                        if (!$this->activateUserInRegister($model->email)) {
//                            $this->setContext();
//                            Blyn::app()->runApp();
                            $loginStatus = BUserIdentity::ERROR_USERNAME_INVALID;
                            $controller->render('registerNewUser', array('form' => $signUpForm, 'model' => $signUpModel,
                                'loginStatus' => $loginStatus,));
                        }
                    } else if ($loginStatus == BUserIdentity::ERROR_NONE) {
                        $this->setContext();
                        Blyn::app()->runApp();
                    }
                } else {
                    $loginStatus = "Email existed";
                    $controller->render('registerNewUser', array('form' => $signUpForm, 'model' => $signUpModel,
                        'loginStatus' => $loginStatus,));
                }
            } else {
                $loginStatus = BUserIdentity::ERROR_USERNAME_INVALID;
                $controller->render('registerNewUser', array('form' => $signUpForm, 'model' => $signUpModel,
                    'loginStatus' => $loginStatus,));
            }
        } else if ($controller->renderLogin) {
            $controller->render('registerNewUser', array('form' => $signUpForm, 'model' => $signUpModel,
                'loginStatus' => $loginStatus,));
        }
    }

    public function renderOpenidLogin($data = NULL) {

        if (is_array($data)) {
            if (isset($data['contact/email'])) {
                //if no account , create one
                $userId = $data['contact/email'];
                $pwd = '1111';
                $user = BUser::find(array('userName' => $userId));
                if (!$user instanceof BUser) {
                    $profile['birthday'] = '01012099';
                    $profile['userName'] = $data['namePerson/first'] . $data['namePerson/last'];
                    $profile['email'] = $userId;
                    BUser::registerWechat($userId, $pwd, $profile);
                    $this->sendMailToOpenidUser($userId, $pwd);
                }
                $loginStatus = BUser::login($userId, $pwd, 0);

                if ($loginStatus < 0) {
                    $controller->layout = "//layouts/column1";
                    $controller->render("registerNotice", array('email' => $loginModel->email));
                    Blyn::app()->end();
                } else if ($loginStatus == BUserIdentity::ERROR_NONE) {
                    $this->setContext();
                    Blyn::app()->runApp();
                }
            }
        }

        //user must login before enter site
//        if (Yii::app()->user->isGuest) {
//            if (get_class($this) === "SiteController") {
//                $this->actionLogin();
//                Yii::app()->end();
//            } elseif (get_class($this) === 'PublicController') {
//                
//            } else {
//                //setContext will init context for blyn application                
//                $this->redirect(array('site/login'));
//                Yii::app()->end();
//            }
//        } 
//        else {
//            Blyn::app()->getUIManager()->setContext();
//            $this->setContext();
//            Blyn::app()->runApp();
//        }
    }

    public function activateUser($key = NULL, $email = NULL) {
        $controller = Yii::app()->getController();

        if ($key != NULL && $email != NULL) {
            $userId = strtolower($email);
            $currentUser = BUser::find(array('userId' => $userId));
            if ($currentUser != NULL && $currentUser->myid == $key) {
                $activateStatus = $currentUser->activate($currentUser);
                if ($activateStatus) {
                    $controller->layout = "//layouts/column1";
                    $controller->render("activateOK");
                    Blyn::app()->end();
                }
            }
        }
    }

    public function activateUserInRegister($email = NULL) {
        $controller = Yii::app()->getController();

        if ($email != NULL) {
            $userId = strtolower($email);
            $currentUser = BUser::find(array('userId' => $userId));
            if ($currentUser != NULL) {
                $activateStatus = $currentUser->activate($currentUser);
                if ($activateStatus) {
                    $controller->layout = "//layouts/column1_2";
                    $controller->render("activateOK");
                    Blyn::app()->end();
                    return true;
                }
            }
        }
        return false;
    }

    public function sendMailToOpenidUser($email = NULL, $pwd = NULL) {

        if (isset($email) && isset($pwd)) {
            ##Send Openid resgistration OK Email
            $to = $email;
            $subject = "www.billyn.net用户Google帐号激活"; //"www.billyn.net Registration";
            $message = "亲爱的用户：<br/>感谢您在我站www.billyn.net注册了您的Google帐号。<br/>今后您可以通过以下帐号登录我站:<br/><br/>"
                    //            ."Welcome to our website!<br/><br/>You, or someone using your email address, has completed registration "
                    //            . "at www.billyn.net. ". "You can complete registration by clicking the following link:<br/><br/>"
                    . "用户名: " . $email . '<br/>'
                    . "密码: " . $pwd . "<br/>"
                    . "您可以在登录本站后修改以上密码。<br/><br/>"
                    . "另注：您也可以在登录本站时选择直接通过Google账号验证。"
                    //            . "<br/><br/>If this is an error, ignore this email and you will be removed from our mailing list."
                    . "<br/><br/>"
                    . "此致"
                    //            ."Regards,"
                    . "<br/> www.billyn.net Team";

            $headers = 'From: noreply@billyn.net' . "\r\n" .
                    'Reply-To: noreply@billyn.net' . "\r\n" .
                    'X-Mailer: PHP/' . phpversion();

            mail($to, $subject, $message, $headers);
        }
    }

    public function setContext(&$data = NULL) {

        $spaceId = NULL;
        $space = NULL;
        $appId = NULL;
        $app = NULL;
        $operationFlowId = NULL;
        $operationId = NULL;
        $operation = NULL;
        $currentNode = NULL;

        //set activeLink 
        if (yii::app()->request->isAjaxRequest) {
            if (!empty($_REQUEST) && isset($_REQUEST['b_ajaxLinkId'])) {
                $linkId = $_REQUEST['b_ajaxLinkId'];
                $this->setActiveLink($linkId);
            }
        } else {
            if (!empty($_REQUEST) && isset($_REQUEST['b_linkId'])) {
                $linkId = $_REQUEST['b_linkId'];
                $this->setActiveLink($linkId);
            }
        }

        //first get previous setting
        ///*
        $lastSpaceData = Blyn::app()->getCurrentUser()->getContextVariable('b_currentSpace');
        if ($lastSpaceData != NULL) {
            $spaceId = $lastSpaceData['id'];
            if ($spaceId != NULL && $spaceId > 0)
                $space = new BSpace($spaceId);
            if ($space instanceof BSpace)
                Blyn::app()->setActiveSpace($space);
        }

        $lastAppData = Blyn::app()->getCurrentUser()->getContextVariable('b_currentApp');
        if ($lastAppData != NULL) {
            $appId = $lastAppData['id'];
            if ($appId != NULL && $appId > 0)
                $app = BApp::getAppById($appId);
            if ($app instanceof BApp)
                Blyn::app()->setActiveApp($app);
        }

        $lastOpFlowData = Blyn::app()->getCurrentUser()->getContextVariable('b_currentOperationFlow');
        if ($lastOpFlowData != NULL) {
            $opFlowId = $lastOpFlowData['id'];
            if ($opFlowId != NULL && $opFlowId > 0)
                $opFlow = new BOperationFlow($opFlowId);
            if ($opFlow instanceof BOperationFlow)
                Blyn::app()->setActiveOperationFlow($opFlow);
        }

        $lastOperationData = Blyn::app()->getCurrentUser()->getContextVariable('b_currentOperation');
        if ($lastOperationData != NULL) {
            $operationId = $lastOperationData['id'];
            if ($operationId != NULL && $operationId > 0)
                $operation = new BOperation($operationId);
            if ($operation instanceof BOperation)
                Blyn::app()->setActiveOperation($operation);
        }

        $currentNodeData = Blyn::app()->getCurrentUser()->getContextVariable('b_currentNode');

        if ($currentNodeData != NULL) {
            $class = $currentNodeData['class'];
            $id = $currentNodeData['id'];
            $currentNode = new $class($id);
            if ($currentNode instanceof BUINode) {
                Blyn::app()->setCurrentNode($currentNode);
                //Blyn::app()->getContextObj()->resetContextVariable(BContextObj::Scope_CurrentNode);
            }
        }

        /*
          if ($this->detectDevice() == 'mobile') {
          $this->setTheme(self::Theme_JMQuery_Wechat);
          yii::app()->getController()->layout = 'jm_layout';
          } else {//by default, set theme to pc_bootstrap
          $this->setTheme(self::Theme_PC_Bootstrap);
          }
         * 
         */

        $device = 'pc';
        if (!empty($_GET) && ((isset($_GET['device']) && ($_GET['device'] == 'weixin' || $_GET['device'] == BUIWXControl::WeChat_Name)) || (isset($_GET['dv']) && ($_GET['dv'] == 'wx')))) {
            $device = 'mobile';
            $parsedData = BUIWXControl::parseRequest();
        } else {
            $parsedData = BUIControl::parseRequest();
        }



        //if (yii::app()->request->isAjaxRequest) {
        if ($device == 'mobile') {
            //手机的默认THEME
            $this->setTheme(self::Theme_JMQuery_Wechat);
//            yii::app()->getController()->layout = 'jm_layout';
            yii::app()->getController()->layout = 'alone';
            //$this->setTheme(self::Theme_Mobile_Bootstrap);
            //$theme = self::Theme_Mobile_Bootstrap;
            //yii::app()->getController()->layout = 'mobile_bootstrap';
        } else {//默认的PC THEME
            $this->setTheme(self::Theme_PC_Bootstrap);
        }
        //}

        $theme = NULL;
        if (isset($_GET['theme']) || isset($_GET['thm'])) {
            if (isset($_GET['thm']))
                $theme = $_GET['thm'];
            if (isset($_GET['theme']))
                $theme = $_GET['theme'];
        }

        if ($theme != NULL) {
            yii::app()->getController()->layout = $theme;
            $this->setTheme($theme);
            if ($theme == self::Theme_Mobile_Bootstrap) {
                yii::app()->getController()->layout = 'mobile_bootstrap';
                //$this->setTheme(self::Theme_Mobile_Bootstrap);
            }
            if ($theme == self::Theme_Admin_Bootstrap) {
                //yii::app()->getController()->layout = 'admin_bootstrap';
            }
        }

        if ($parsedData != NULL) {
            $this->updateControl = isset($parsedData['updateControl']) ? $parsedData['updateControl'] : NULL;
            $this->senderControl = isset($parsedData['activeControl']) ? $parsedData['activeControl'] : NULL;
            //if ajax request, only show view from parsed data
            if (yii::app()->request->isAjaxRequest) {
                $this->startView['view'] = $parsedData['view'];
                $this->startView['data'] = $parsedData['data'];
            }
        }

        //set active Space, if not specify, set personal Space as default Space
        if (Blyn::app()->getActiveSpace() == NULL) {
            $personalSpace = Blyn::app()->getCurrentUser()->getPersonalSpace();
            Blyn::app()->setActiveSpace($personalSpace);
            Blyn::app()->setCurrentNode($personalSpace);
        }


        //if not specify Space application, set SpaceEngine as activeApp
        if (Blyn::app()->getActiveApp() == NULL) {
            $spaceEngine = Blyn::app()->getActiveSpace()->getSpaceEngine();
            Blyn::app()->setActiveApp($spaceEngine);
            Blyn::app()->setCurrentNode($spaceEngine);
        }

        if (isset($data['renderNode']) && $data['renderNode'] == BUIBlyn::HomeNode_PersonalSpace) {
            $currentUser = Blyn::app()->getCurrentUser();
            $personalSpace = Blyn::app()->setActiveSpace($currentUser->getPersonalSpace());
            return Blyn::app()->setCurrentNode($personalSpace);
        }

        //Blyn::app()->setCurrentNode($currentNode);
    }

    /**
     * render app will judge ajax request
     * @param type $data
     */
    public function renderApp($data = NULL) {

        $this->startRender();

        yii::app()->end();
    }

    public function startRender($config = NULL) {

        $controller = yii::app()->getController();
        $request = yii::app()->request;
        //$views = array();
        if ($request->isAjaxRequest) {
            if ($this->startView != NULL) {
                $view = isset($this->startView['view']) ? $this->startView['view'] : NULL;
                $data = isset($this->startView['data']) ? $this->startView['data'] : NULL;
                $updateControl = $this->updateControl;
                //$senderControl = $this->senderControl;

                $this->resetCurrentContextVariable();
                if ($updateControl instanceof BUIControl) {
                    $updateControl->renderContent();
                    //$data['control'] = $control;
                } else {
                    $this->renderView($view, $data);
                }

                /*
                  if ($updateControl->layoutView == 'blyn_layout')
                  $this->renderView($updateControl->layoutView, $data);
                  else
                  $this->renderView($view, $data);
                  //    $updateControl->render();
                 * 
                 */
            }
        } else {
            $this->resetCurrentContextVariable();
            $controller->render("startPage3");
        }

        if ($this->gotoNode !== FALSE) {
            $node = $this->gotoNode['node'];
            $this->gotoNode($node);
        }

        $this->postStartRender();

        //Blyn::app()->getContextObj()->saveContextVariable();
        //yii::app()->end();
    }

    public function postStartRender() {

        $tranObj = Blyn::app()->getContextObj();

        //$ContextApp = Blyn::app()->getContextApp();
        /*
          $currentScreen = Blyn::app()->getUIManager()->getCurrentScreen();
          $currentScreenFlow = Blyn::app()->getUIManager()->getCurrentScreenFlow();

          if ($currentScreenFlow != NULL) {
          $sf = $currentScreenFlow;
          $sf->addContextVariable(BUIScreenFlow::CONTEXT_VARIABLE_SCREENFLOW_INDEX, $sf->getIndex());
          //$sf->addContextVariable(BContextObj::VariableName_Id, $sf->getId());
          //$sf->addContextVariable(BContextObj::VariableName_Class, $sf->getName());
          $tranObj->addContextVariable(BContextObj::Scope_Blyn, BContextObj::V_CurrentScreenFlowId, $sf->getId());
          $tranObj->addContextVariable(BContextObj::Scope_Blyn, BContextObj::V_CurrentScreenFlowName, $sf->getName());

          $tranObj->resetContextVariable(BContextObj::Scope_Screen);
          } else {
          $tranObj->resetContextVariable(BContextObj::Scope_ScreenFlow);
          //$tranObj->addContextVariable(BContextObj::VariableName_CurrentScreen, BContextObj::VariableName_Id, $this->getId());
          //$tranObj->addContextVariable(BContextObj::VariableName_CurrentScreen, BContextObj::VariableName_Class, get_class($this));
          $tranObj->addContextVariable(BContextObj::Scope_Blyn, BContextObj::V_CurrentScreenId, $currentScreen->getId());
          $tranObj->addContextVariable(BContextObj::Scope_Blyn, BContextObj::V_CurrentScreenName, $currentScreen->getName());
          }
         * 
         */

        //first empty all setting in current node scope
        $tranObj->resetContextVariable(BContextObj::Scope_CurrentNode, BContextObj::V_CurrentNodeId);
        $tranObj->resetContextVariable(BContextObj::Scope_CurrentNode, BContextObj::V_CurrentSpaceId);
        $tranObj->resetContextVariable(BContextObj::Scope_CurrentNode, BContextObj::V_CurrentAppId);
        $tranObj->resetContextVariable(BContextObj::Scope_CurrentNode, BContextObj::V_CurrentOperationId);
        $tranObj->resetContextVariable(BContextObj::Scope_CurrentNode, BContextObj::V_CurrentOperationFlowId);
        $tranObj->resetContextVariable(BContextObj::Scope_CurrentNode, BContextObj::V_CurrentScreenFlowId);
        $tranObj->resetContextVariable(BContextObj::Scope_CurrentNode, BContextObj::V_CurrentScreenId);

        //then add current variable setting into current node
        if (Blyn::app()->getCurrentNode() instanceof BNode) {
            $node = Blyn::app()->getCurrentNode();
            $nodeId = strtolower(get_class($node)) . '_' . $node->getId();
            $tranObj->addContextVariable(BContextObj::Scope_CurrentNode, BContextObj::V_CurrentNodeId, $nodeId);
            Blyn::app()->getCurrentUser()->addContextVariable('b_currentNode', array('class' => get_class($node), 'id' => $node->getId()));
        }

        if (Blyn::app()->getActiveSpace() instanceof BSpace) {
            $spaceId = Blyn::app()->getActiveSpace()->getId();
            $tranObj->addContextVariable(BContextObj::Scope_CurrentNode, BContextObj::V_CurrentSpaceId, 'space_' . $spaceId);
            Blyn::app()->getCurrentUser()->addContextVariable('b_currentSpace', array('id' => $spaceId));
        }

        if (Blyn::app()->getActiveApp() instanceof BApp) {
            $appId = Blyn::app()->getActiveApp()->getId();
            $tranObj->addContextVariable(BContextObj::Scope_CurrentNode, BContextObj::V_CurrentAppId, 'app_' . $appId);
            Blyn::app()->getCurrentUser()->addContextVariable('b_currentApp', array('id' => $appId));
        }

        if (Blyn::app()->getActiveOperation() instanceof BOperation) {
            $operationId = Blyn::app()->getActiveOperation()->getId();
            $tranObj->addContextVariable(BContextObj::Scope_CurrentNode, BContextObj::V_CurrentOperationId, 'operation_' . $operationId);
            Blyn::app()->getCurrentUser()->addContextVariable('b_currentOperation', array('id' => $operationId));
        }

        if (Blyn::app()->getActiveOperationFlow() instanceof BOperationFlow) {
            $operationFlowId = Blyn::app()->getActiveOperationFlow()->getId();
            $tranObj->addContextVariable(BContextObj::Scope_CurrentNode, BContextObj::V_CurrentOperationFlowId, 'operationFlow_' . $operationFlowId);
            //$index = Blyn::app()->getActiveOperationFlow()->getIndex();
            $index = 0;
            Blyn::app()->getCurrentUser()->addContextVariable('b_currentOperationFlow', array('id' => $operationFlowId, 'index' => $index));
        }

        if (Blyn::app()->getUIManager()->getCurrentScreen() instanceof BUIScreen) {
            $screenId = Blyn::app()->getUIManager()->getCurrentScreen()->getId();
            $tranObj->addContextVariable(BContextObj::Scope_CurrentNode, BContextObj::V_CurrentScreenId, $screenId);
            $screenData = array('class' => get_class(Blyn::app()->getUIManager()->getCurrentScreen()));
            if (Blyn::app()->getCurrentNode() instanceof BNode) {
                if (Blyn::app()->getCurrentNode()->getId() != NULL) {
                    $screenData['nodeId'] = Blyn::app()->getCurrentNode()->getId();
                    $screenData['nodeClass'] = get_class(Blyn::app()->getCurrentNode());
                }
            }
            Blyn::app()->getCurrentUser()->addContextVariable('b_currentScreen', $screenData);
        }

        if (Blyn::app()->getUIManager()->getCurrentScreenFlow() instanceof BUIScreenFlow) {
            $screenFlow = Blyn::app()->getUIManager()->getCurrentScreenFlow();
            $screenFlowId = $screenFlow->getId();
            $tranObj->addContextVariable(BContextObj::Scope_CurrentNode, BContextObj::V_CurrentScreenFlowId, $screenFlowId);
            $index = $screenFlow->getIndex();
            if ($index != NULL && $index > 0)
                $screenFlow->addContextVariable(BUIScreenFlow::CONTEXT_VARIABLE_SCREENFLOW_INDEX, $index);

            Blyn::app()->getCurrentUser()->addContextVariable('b_current_screenFlow', array('id' => $screenFlowId, 'index' => $index,
                'nodeId' => Blyn::app()->getCurrentNode()->getId(), 'nodeClass' => get_class(Blyn::app()->getCurrentNode())));
        }

        $tranObj->saveContextVariable();
    }

    public function getLinks($isReload = false) {

        //$this->links = array();
        //Context variable name
        $T_appLinks = 'appLinks';

        /* because get application links is a time-expensive operations, save result into application Context variable,
         * unless require reload or appLinks is null, no need retrieve links each time
         */
        //$appLinks = Blyn::app()->getCurrentUser()->getContextVariable($T_appLinks);
        //$appLinks = Blyn::app()->getCacheManager()->getCache($T_appLinks);
        $appLinks = $this->links;
        if ($appLinks != NULL && !$isReload)
            $this->links = $appLinks;
        else {
            //populate main menu links
            $billeenStr = Yii::t('site', 'billeen');
            $mySpaceStr = Yii::t('site', 'My Space');
            $mySpaceLinkBeforeSend = 'function(){' . $this->showLoadGif .
                    '$("ul.nav li.active").removeClass("active");
                $("li:contains(\'' . $mySpaceStr . '\')").addClass("active");
                }';
            $this->mySpaceLinkBeforeSend = $mySpaceLinkBeforeSend;

            $mySpacesStr = Yii::t('site', 'My Spaces');
            $mySpacesLinkBeforeSend = 'function(){' . $this->showLoadGif .
                    '$("ul.nav li.active").removeClass("active");
                $("li:contains(\'' . $mySpacesStr . '\')").addClass("active");
                }';
            $this->mySpacesLinkBeforeSend = $mySpacesLinkBeforeSend;

            $spaceStoreStr = Yii::t('site', 'Space Store');
            $spaceStoreLinkBeforeSend = 'function(){' . $this->showLoadGif .
                    '$("ul.nav li.active").removeClass("active");
                $("li:contains(\'' . $spaceStoreStr . '\')").addClass("active");
                }';

            $createSpaceStr = Yii::t('site', 'Create Space');
            $logOutStr = Yii::t('site', 'Logout');
//            $personalSpaceLink = Blyn::app()->getCurrentUser()->getPersonalSpace()->getUIManager()->getAjaxLink('My Space', array('ajaxOptions' => array('beforeSend' => $mySpaceLinkBeforeSend)));
            $personalSpaceLink = Blyn::app()->getCurrentUser()->getPersonalSpace()->getUIManager()->getAjaxLink($mySpaceStr, array('ajaxOptions' => array('beforeSend' => $mySpaceLinkBeforeSend)));
            $bandBilleenLink = Blyn::app()->getCurrentUser()->getPersonalSpace()->getUIManager()->getAjaxLink('<img src="./images/global.jpg" width="25" height="25"  class="img-rounded"> </img>' . $billeenStr, array('ajaxOptions' => array('beforeSend' => $mySpaceLinkBeforeSend), 'htmlOptions' => array('class' => "brand", 'style' => "padding-left: 15px;padding-right: 10px")));
            $mySpacesLink = Blyn::app()->getCurrentUser()->getPersonalSpace()->
                            getAppByName('BPersonalApp')->getOperation(BPersonalApp::OPERATION_LISTMYSpace)->getUIManager()->getAjaxLink($mySpacesStr, array('ajaxOptions' => array('beforeSend' => $mySpacesLinkBeforeSend)));
            $spaceStoreLink = Blyn::app()->getCurrentUser()->getPersonalSpace()->
                            getAppByName('BPersonalApp')->getOperation(BPersonalApp::OPERATION_JOINSpace)->getUIManager()->getAjaxLink($spaceStoreStr, array('ajaxOptions' => array('beforeSend' => $spaceStoreLinkBeforeSend)));
            $createSpaceLink = Blyn::app()->getCurrentUser()->getPersonalSpace()->
                            getAppByName('BPersonalApp')->getOperation(BPersonalApp::OPERATION_CREATESpace)->getUIManager()->getAjaxLink($createSpaceStr, array(
                'htmlOptions' => array('class' => 'btn btn-success'),
                'ajaxOptions' => array('beforeSend' => $mySpacesLinkBeforeSend)));
            $joinSpaceLink = Blyn::app()->getCurrentUser()->getPersonalSpace()->
                            getAppByName('BPersonalApp')->getOperation(BPersonalApp::OPERATION_JOINSpace)->getUIManager()->getAjaxLink($spaceStoreStr, array(
                'htmlOptions' => array('class' => 'btn btn-success'),
                'ajaxOptions' => array('beforeSend' => $spaceStoreLinkBeforeSend)));

            $mainMenu = array(
                //'mySpace' => array('label' => 'My Space', 'url' => array('site/index'), 'ajaxUrl' => $this->getHomeUrl(array('ajaxLink' => array('name' => 'My Space', 'ajaxOptions' => array('beforeSend' => $mySpaceLinkBeforeSend))))),
                'mySpace' => array('label' => 'My Space', 'url' => array('site/index'), 'ajaxUrl' => $personalSpaceLink),
                'bandBilleen' => array('label' => $billeenStr, 'ajaxUrl' => $bandBilleenLink),
                // 'SpaceStore' => array('label' => 'Space Store', 'url' => array('site/SpaceStore')),
                //'mySpaces' => array('label' => 'My Spaces', 'ajaxUrl' => $this->getUrl(array('ajaxLink' => array('name' => 'My Spaces', 'ajaxOptions' => array('beforeSend' => $mySpacesLinkBeforeSend))))),
                'mySpaces' => array('label' => 'My Spaces', 'ajaxUrl' => $mySpacesLink),
                'SpaceStore' => array('label' => 'My Spaces', 'ajaxUrl' => $spaceStoreLink),
                'logOut' => array('label' => $logOutStr . '(' . Yii::app()->user->name . ')', 'url' => yii::app()->getController()->createUrl('/site/logout')));

            $this->links['mainMenu'] = $mainMenu;
            $this->links['createSpace'] = array('label' => 'Create Space', 'ajaxUrl' => $createSpaceLink);
            $this->links['joinSpace'] = array('label' => 'Join Space', 'ajaxUrl' => $joinSpaceLink);

            /* populate working Spaces and following Spaces */
            $app = Blyn::app();
            //$spaces = array();
            if ($isReload)
                $userSpaces = $app->getCurrentUser()->getUserSpacesReloaded();
            else
                $userSpaces = $app->getCurrentUser()->getUserSpaces();
            $adminSpaces = $userSpaces['adminSpaces'];
            $memberSpaces = $userSpaces['memberSpaces'];
            $customerSpaces = $userSpaces['customerSpaces'];

            //remove duplicate space from member and customer list
            foreach ($adminSpaces as $spaceId => $roles) {
                if (isset($memberSpaces[$spaceId]))
                    unset($memberSpaces[$spaceId]);
                if (isset($customerSpaces[$spaceId]))
                    unset($customerSpaces[$spaceId]);
            }

            foreach ($memberSpaces as $spaceId => $roles) {
                if (isset($customerSpaces[$spaceId]))
                    unset($customerSpaces[$spaceId]);
            }

            $adminSpaceLinks = array();
            $workingSpaceLinks = array();
            $followingSpaceLinks = array();

            foreach ($adminSpaces as $spaceId => $roles) {
                $space = new BSpace($spaceId);
                //if ($space->getVisible()) {
                $menuItem = array();
                $menuItem['label'] = $space->getName();
                //$menuItem['url'] = $space->getSpaceEngine()->getUIManager()->getUrl(array('rtp' => $type));
                $menuItem['url'] = $space->getUIManager()->getUrl();
                //$menuItem['ajaxUrl'] = $space->getSpaceEngine()->getUIManager()->getUrl(array('ajaxLink' => array('name' => $space->getName(), 'ajaxOptions' => array('beforeSend' => $this->mySpacesLinkBeforeSend))));
                $menuItem['ajaxUrl'] = $space->getUIManager()->getAjaxLink($space->getName(), array('ajaxOptions' => array('beforeSend' => $this->mySpacesLinkBeforeSend)));

                $adminSpaceLinks[$spaceId] = $menuItem;
                //}
            }

            foreach ($memberSpaces as $spaceId => $roles) {
                $space = new BSpace($spaceId);
                //if ($space->getVisible()) {
                $menuItem = array();
                $menuItem['label'] = $space->getName();
                //$menuItem['url'] = $space->getSpaceEngine()->getUIManager()->getUrl(array('rtp' => $type));
                $menuItem['url'] = $space->getUIManager()->getUrl();
                //$menuItem['ajaxUrl'] = $space->getSpaceEngine()->getUIManager()->getUrl(array('ajaxLink' => array('name' => $space->getName(), 'ajaxOptions' => array('beforeSend' => $this->mySpacesLinkBeforeSend))));
                $menuItem['ajaxUrl'] = $space->getUIManager()->getAjaxLink($space->getName(), array('ajaxOptions' => array('beforeSend' => $this->mySpacesLinkBeforeSend)));

                $workingSpaceLinks[$spaceId] = $menuItem;
                //}
            }

            foreach ($customerSpaces as $spaceId => $roles) {
                $space = new BSpace($spaceId);
                //if ($space->getVisible()) {
                $menuItem = array();
                $menuItem['label'] = $space->getName();
                //$menuItem['url'] = $space->getSpaceEngine()->getUIManager()->getUrl(array('rtp' => $type));
                $menuItem['url'] = $space->getUIManager()->getUrl();
                //$menuItem['ajaxUrl'] = $space->getSpaceEngine()->getUIManager()->getUrl(array('ajaxLink' => array('name' => $space->getName(), 'ajaxOptions' => array('beforeSend' => $this->mySpacesLinkBeforeSend))));
                $menuItem['ajaxUrl'] = $space->getUIManager()->getAjaxLink($space->getName(), array('ajaxOptions' => array('beforeSend' => $this->mySpacesLinkBeforeSend)));

                $followingSpaceLinks[$spaceId] = $menuItem;
                //}
            }

            $this->links['adminSpaceLinks'] = $adminSpaceLinks;

            $this->links['workingSpaceLinks'] = $workingSpaceLinks;

            $this->links['followingSpaceLinks'] = $followingSpaceLinks;

            //Blyn::app()->getCurrentUser()->addContextVariable($T_appLinks, $this->links);
            //Blyn::app()->getCacheManager()->addCache($T_appLinks, $this->links);
        }

        return $this->links;
    }

    protected function registerMenu($event) {

        $this->menus[self::Menu_WorkingSpacesLinks] = array();
        $this->menus[self::Menu_FollowingSpacesLinks] = array();

        parent::registerMenu($event);

        $menuManager = $this->getMenuManager();

        $mySpaceLinkBeforeSend = 'function(){' . $this->showLoadGif .
                '$("ul.nav li.active").removeClass("active");
                $("li:contains(\'My Space\')").addClass("active");
                }';
        $this->mySpaceLinkBeforeSend = $mySpaceLinkBeforeSend;

        $mySpacesLinkBeforeSend = 'function(){' . $this->showLoadGif .
                '$("ul.nav li.active").removeClass("active");
                $("li:contains(\'My Spaces\')").addClass("active");
                }';
        $this->mySpacesLinkBeforeSend = $mySpacesLinkBeforeSend;

        $mainMenu = array(
            'items' => array(
                'mySpace' => array('label' => 'My Space', 'url' => array('site/index'), 'ajaxUrl' => $this->getHomeUrl(array('ajaxLink' => array('name' => 'My Space', 'ajaxOptions' => array('beforeSend' => $mySpaceLinkBeforeSend))))),
                'SpaceStore' => array('label' => 'Space Store', 'url' => array('site/SpaceStore')),
                'mySpaces' => array('label' => 'My Spaces', 'ajaxUrl' => $this->getUrl(array('ajaxLink' => array('name' => 'My Spaces', 'ajaxOptions' => array('beforeSend' => $mySpacesLinkBeforeSend, 'data' => array('mySpacesLink' => TRUE)))))),
                'logOut' => array('label' => 'logout(' . Yii::app()->user->name . ')',
                    'url' => array('/site/logout'))));

        $spaceStoreLinkBeforeSend = 'function(){' . $this->showLoadGif .
                '$("ul.nav li.active").removeClass("active");
                $("li:contains(\'Space Store\')").addClass("active");
                }';

        $menuManager->addMenu(self::MAINMENU, $mainMenu);

        $savedLeftMenu = $menuManager->getMenu(self::LEFTMENU);

        //$leftMenu = $savedLeftMenu;

        $app = Blyn::app();
        $pSpace = $app->getCurrentUser()->getPersonalSpace();
        $psApps = $pSpace->getSpaceEngine()->doOperation(BSpaceEngine::GETAppSOPERATION, array('Space' => $pSpace));
        //$psApps = $pSpace->getApps();
        //add unchange menu into Context variable and get only from saved menu
        $savedLeftMenu = NULL;
        if ($savedLeftMenu == NULL || (isset($savedLeftMenu['items']) && $savedLeftMenu['items']) == NULL) {

            $leftMenu = array('items' => array());
            //$menuManager->addMenuItem($leftMenu, array('label' => 'My Space'));

            foreach ($psApps as $sApp) {
                if (get_class($sApp) == "BPersonalApp") {
                    $oppCreateUrl = $sApp->getOperationByName(BPersonalApp::OPERATION_CREATESpace)->getUIManager()->getUrl();
                    $oppCreateAjaxUrl = $sApp->getOperationByName(BPersonalApp::OPERATION_CREATESpace)->getUIManager()->getUrl(array('ajaxLink' => array('name' => 'creat a Space', 'ajaxOptions' => array('beforeSend' => $mySpaceLinkBeforeSend))));
                    $menuManager->addMenuItem($leftMenu, array('label' => 'create a Space', 'ajaxUrl' => $oppCreateAjaxUrl,
                        'url' => $oppCreateUrl));

                    //$oppJoinUrl = $sApp->getOperationByName(BPersonalApp::OPERATION_JOINSpace)->getUIManager()->getUrl();
                    //$oppJoinAjaxUrl = $sApp->getOperationByName(BPersonalApp::OPERATION_JOINSpace)->getUIManager()->getUrl(array('ajaxLink' => array('name' => 'join a Space', 'ajaxOptions' => array('beforeSend' => $spaceStoreLinkBeforeSend))));
                    $spaceStoreAjaxUrl = $sApp->getOperationByName(BPersonalApp::OPERATION_JOINSpace)->getUIManager()->getUrl(array('ajaxLink' => array('name' => 'Space Store', 'ajaxOptions' => array('beforeSend' => $spaceStoreLinkBeforeSend))));
                    $mainMenu = Blyn::app()->getAppUI()->getMenu(BUIBlyn::MAINMENU);
                    $mainMenu['items']['SpaceStore'] = array('label' => 'Space Store', 'url' => array('site/SpaceStore'), 'ajaxUrl' => $spaceStoreAjaxUrl);
                    $menuManager->addMenu(self::MAINMENU, $mainMenu);
                    //$menuManager->addMenuItem($leftMenu, array('label' => 'join a Space', 'ajaxUrl' => $oppJoinAjaxUrl,'url' => $oppJoinUrl));

                    break;
                }
            }

            $isContextMenu = TRUE;
            $menuManager->addMenu(self::LEFTMENU, $leftMenu);
        }

        //render workingteam of Spaces' navigation menu  
        $menuManager->addMenuItem($leftMenu, array('label' => 'My Working Spaces'));

        $spaces = array();
        $wadmin_Spaces = $app->getCurrentUser()->getCurrentUserSpaces(BUser::WORKTEAMADMINROLE);
        $sadmin_Spaces = $app->getCurrentUser()->getCurrentUserSpaces(BUser::SERVEDTEAMADMINROLE);
        $wmber_Spaces = $app->getCurrentUser()->getCurrentUserSpaces(BUser::WORKTEAMMEMBERROLE);
        $smber_Spaces = $app->getCurrentUser()->getCurrentUserSpaces(BUser::SERVEDTEAMMEMBERROLE);
        $spaceAdmin_Spaces = $app->getCurrentUser()->getCurrentUserSpaces(BBasicRolesTemplate::Space_ADMIN_ROLE);
        //      $spaceMember_Spaces = $app->getCurrentUser()->getCurrentUserSpaces(BBasicRolesTemplate::SERVEDTEAM_MEMBER_ROLE);

        foreach ($wadmin_Spaces as $key => $value) {
            $spaces[$key] = $value;
        }

        foreach ($wmber_Spaces as $key => $value) {
            $spaces[$key] = $value;
        }

        foreach ($sadmin_Spaces as $key => $value) {
            $spaces[$key] = $value;
        }

        foreach ($spaceAdmin_Spaces as $key => $value) {
            $spaces[$key] = $value;
        }

        /*
          foreach ($spaceMember_Spaces as $key => $value) {
          $spaces[$key] = $value;
          }
         * 
         */

        foreach ($spaces as $space) {
            $this->addSpaceMenuItem($leftMenu, $space, BSpace::WORKTEAMTYPE);
        }

        //render servedteams' navigation menu
        $menuManager->addMenuItem($leftMenu, array('label' => 'My Joined Spaces'));

        $idList = array();

        foreach ($spaces as $space) {
            array_push($idList, $space->getId());
        }

        foreach ($smber_Spaces as $space) {
            $sId = $space->getId();
            if (!in_array($sId, $idList))
                $this->addSpaceMenuItem($leftMenu, $space, BSpace::SERVEDTEAMTYPE);
        }

        $menuManager->addMenu(self::LEFTMENU, $leftMenu);
        if (isset($this->menus[self::Menu_WorkingSpacesLinks]))
            $menuManager->addMenu("WorkingSpaceLinks", $this->menus[self::Menu_WorkingSpacesLinks]);
        if (isset($this->menus[self::Menu_FollowingSpacesLinks]))
            $menuManager->addMenu("FollowingSpaceLinks", $this->menus[self::Menu_FollowingSpacesLinks]);
    }

    protected function addSpaceMenuItem(&$menu, $space, $type) {
        $menuManager = $this->getMenuManager();
        if ($space->getVisible()) {
            $menuItem = array();
            $menuItem['label'] = $space->getName();
            $menuItem['url'] = $space->getSpaceEngine()->getUIManager()->getUrl(array('rtp' => $type));
            $menuItem['ajaxUrl'] = $space->getSpaceEngine()->getUIManager()->getUrl(array('ajaxLink' => array('name' => $space->getName(), 'ajaxOptions' => array('beforeSend' => $this->mySpacesLinkBeforeSend))));
            //$url = $menuItem['url'];
            //$menuItem['url'] = $this->addTeamTypeIntoUrL($url, $type);
            $menuManager->addMenuItem($menu, $menuItem);

            if ($type == BSpace::WORKTEAMTYPE) {

                if (!isset($this->menus[self::Menu_WorkingSpacesLinks])) {
                    $this->menus[self::Menu_WorkingSpacesLinks] = array();
                }

                array_push($this->menus[self::Menu_WorkingSpacesLinks], $menuItem);
            }
            if ($type == BSpace::SERVEDTEAMTYPE) {
                if (!isset($this->menus[self::Menu_FollowingSpacesLinks])) {
                    $this->menus[self::Menu_FollowingSpacesLinks] = array();
                }

                array_push($this->menus[self::Menu_FollowingSpacesLinks], $menuItem);
            }
        }
    }

    public static function detectDevice() {

        /*

          $iPod = stripos($_SERVER['HTTP_USER_AGENT'], "iPod");
          $iPhone = stripos($_SERVER['HTTP_USER_AGENT'], "iPhone");
          $iPad = stripos($_SERVER['HTTP_USER_AGENT'], "iPad");
          if (stripos($_SERVER['HTTP_USER_AGENT'], "Android") && stripos($_SERVER['HTTP_USER_AGENT'], "mobile")) {
          $Android = true;
          } else if (stripos($_SERVER['HTTP_USER_AGENT'], "Android")) {
          $Android = false;
          $AndroidTablet = true;
          } else {
          $Android = false;
          $AndroidTablet = false;
          }
          $webOS = stripos($_SERVER['HTTP_USER_AGENT'], "webOS");
          $BlackBerry = stripos($_SERVER['HTTP_USER_AGENT'], "BlackBerry");
          $RimTablet = stripos($_SERVER['HTTP_USER_AGENT'], "RIM Tablet");

          if ($iPhone) {
          return BUIBlyn::DEVICE_IPHONE;
          }

          if ($iPad) {
          return BUIBlyn::DEVICE_IPAD;
          }

          if ($AndroidTablet) {
          return BUIBlyn::DEVICE_ANDROID_TABLET;
          }

          if ($Android)
          return BUIBlyn::DEVICE_ANDROID;

          if ($iPod || $BlackBerry || $Android || $webOS) {
          return BUIBlyn::DEVICE_MOBILE_GENERAL;
          }

          if ($RimTablet)
          return BUIBlyn::DEVICE_TABLET_GENERAL;


          $mobile_browser = '0';

          if (preg_match('/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|android)/i', strtolower($_SERVER['HTTP_USER_AGENT']))) {
          $mobile_browser++;
          }

          if ((strpos(strtolower($_SERVER['HTTP_ACCEPT']), 'application/vnd.wap.xhtml+xml') > 0) or ((isset($_SERVER['HTTP_X_WAP_PROFILE']) or isset($_SERVER['HTTP_PROFILE'])))) {
          $mobile_browser++;
          }

          $mobile_ua = strtolower(substr($_SERVER['HTTP_USER_AGENT'], 0, 4));
          $mobile_agents = array(
          'w3c ', 'acs-', 'alav', 'alca', 'amoi', 'audi', 'avan', 'benq', 'bird', 'blac',
          'blaz', 'brew', 'cell', 'cldc', 'cmd-', 'dang', 'doco', 'eric', 'hipt', 'inno',
          'ipaq', 'java', 'jigs', 'kddi', 'keji', 'leno', 'lg-c', 'lg-d', 'lg-g', 'lge-',
          'maui', 'maxo', 'midp', 'mits', 'mmef', 'mobi', 'mot-', 'moto', 'mwbp', 'nec-',
          'newt', 'noki', 'oper', 'palm', 'pana', 'pant', 'phil', 'play', 'port', 'prox',
          'qwap', 'sage', 'sams', 'sany', 'sch-', 'sec-', 'send', 'seri', 'sgh-', 'shar',
          'sie-', 'siem', 'smal', 'smar', 'sony', 'sph-', 'symb', 't-mo', 'teli', 'tim-',
          'tosh', 'tsm-', 'upg1', 'upsi', 'vk-v', 'voda', 'wap-', 'wapa', 'wapi', 'wapp',
          'wapr', 'webc', 'winw', 'winw', 'xda ', 'xda-');

          if (in_array($mobile_ua, $mobile_agents)) {
          $mobile_browser++;
          }

          if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'OperaMini') > 0) {
          $mobile_browser++;
          }

          if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'windows') > 0) {
          $mobile_browser = 0;
          }

          if ($mobile_browser > 0) {
          return BUIBlyn::DEVICE_MOBILE_GENERAL;
          }

         * Ï
         */

        return FALSE;
    }

    public function getUrl($data = NULL) {

        $ajaxUrl = $this->getAjaxUrl($data);

        if ($ajaxUrl != NULL)
            return $ajaxUrl;

        if (is_array($data) && $data != NULL)
            return yii::app()->createUrl('site/index', $data);

        return array('site/index');
    }

    public function getHomeUrl($data) {

        $currentUser = Blyn::app()->getCurrentUser();

        $personalSpace = $currentUser->getPersonalSpace();

        //$url = $personalSpace->getUIManager()->getUrl($data);
        $url = $personalSpace->getUIManager()->getAjaxLink($data);

        return $url;
    }

    public function onRender($data = NULL) {
        parent::onRender($data);
        $this->layoutView = 'blyn_layout';
        if (Blyn::app()->getActiveSpace() != NULL) {
            $uiSpace = Blyn::app()->getActiveSpace()->getUIManager();
        } else {
            $uiSpace = new BUISpace();
        }
        $this->addControl($uiSpace, 'activeSpace');
        Blyn::app()->setUIManager($this);
    }

    public function getCurrentScreen() {
        if (!Blyn::app()->getCurrentNode() instanceof BlynApp)
            return Blyn::app()->getCurrentNode()->getUIManager()->getCurrentScreen();
        else {
            if ($this->currentScreen == NULL)
                $this->currentScreen = new BUIScreen('screen-for-blyn');
            return $this->currentScreen;
        }
    }

    public function getCurrentScreenFlow() {
        if (!Blyn::app()->getCurrentNode() instanceof BlynApp)
            return Blyn::app()->getCurrentNode()->getUIManager()->getCurrentScreenFlow();
        else
            return new BUIScreenFlow('screenflow-for-blyn');
    }

    public function gotoScreenFlow($screenFlow, $data = array()) {
        //parent::gotoScreenFlow($name, $data);
        if ($screenFlow instanceof BUIScreenFlow)
            $this->setCurrentScreenFlow($screenFlow);
        //$this->postStartRender();
        //Blyn::app()->getUIManager()->r
        //yii::app()->end();
        //run again to render
        $this->renderApp();
    }

    public function gotoNode($node = NULL, $data = array()) {

        if ($node instanceof BNode) {
            Blyn::app()->setCurrentNode($node);

            $this->updateControl = $node->getUIManager();
            //Blyn::app()->getCurrentUser()->addContextVariable('gotoNode', $node->getUIManager()->parseIntoArray());
            $this->renderApp();
        }
    }

    /**
     * this function will reset context variables according to context change
     * for example, screen change, screenflow change and so on
     * @param type $scope
     * @param type $name
     */
    protected function resetCurrentContextVariable($scope = NULL, $name = NULL) {

        $contextObj = Blyn::app()->getContextObj();

        $previousScreenId = $contextObj->getContextVariable(BContextObj::Scope_CurrentNode, BContextObj::V_CurrentScreenId);

        $currentScreenId = NULL;
        if (Blyn::app()->getUIManager()->getCurrentScreen() != NULL)
            $currentScreenId = Blyn::app()->getUIManager()->getCurrentScreen()->getId();

        if ($currentScreenId != NULL && $previousScreenId != $currentScreenId) {
            $contextObj->resetContextVariable(BContextObj::Scope_Screen);
        }

        $previousScreenFlowId = $contextObj->getContextVariable(BContextObj::Scope_CurrentNode, BContextObj::V_CurrentScreenFlowId);

        //$currentScreenFlowId = NULL;
        //if (Blyn::app()->getUIManager()->getCurrentScreenFlow() != NULL)
        //$currentScreenFlowId = Blyn::app()->getUIManager()->getCurrentScreenFlow()->getId();
        //if ($currentScreenFlowId != NULL && $previousScreenFlowId != $currentScreenFlowId) {
        //$contextObj->resetContextVariable(BContextObj::Scope_ScreenFlow);
        //}

        $previousCurrentNodeId = $contextObj->getContextVariable(BContextObj::Scope_CurrentNode, BContextObj::V_CurrentNodeId);
        $currentNodeId = NULL;
        if (Blyn::app()->getCurrentNode() != NULL) {
            $currentNode = Blyn::app()->getCurrentNode();
            $currentNodeId = strtolower(get_class($currentNode)) . '_' . $currentNode->getId();
        }

        if ($currentNodeId == NULL || $previousCurrentNodeId != $currentNodeId) {
            $contextObj->resetContextVariable(BContextObj::Scope_CurrentNode);
        }

        $previousOperationId = $contextObj->getContextVariable(BContextObj::Scope_CurrentNode, BContextObj::V_CurrentOperationId);
        $operationId = NULL;
        if (Blyn::app()->getActiveOperation() instanceof BOperation) {
            $operationId = Blyn::app()->getActiveOperation()->getId();
        }

        if ($operationId == NULL || $previousOperationId != 'operation_' . $operationId) {
            $contextObj->resetContextVariable(BContextObj::Scope_Operation);
        }

        $previousOperationFlowId = $contextObj->getContextVariable(BContextObj::Scope_CurrentNode, BContextObj::V_CurrentOperationFlowId);
        $operationFlowId = NULL;
        if (Blyn::app()->getActiveOperationFlow() instanceof BOperationFlow) {
            $operationFlowId = Blyn::app()->getActiveOperationFlow()->getId();
        }

        if ($operationFlowId == NULL || $previousOperationFlowId != 'operationFlow_' . $operationFlowId) {
            $contextObj->resetContextVariable(BContextObj::Scope_OperationFlow);
        }

        $previousAppId = $contextObj->getContextVariable(BContextObj::Scope_CurrentNode, BContextObj::V_CurrentAppId);
        $appId = NULL;
        if (Blyn::app()->getActiveApp() instanceof BApp) {
            $appId = Blyn::app()->getActiveApp()->getId();
        }

        if ($appId == NULL || $previousAppId != 'app_' . $appId) {
            $contextObj->resetContextVariable(BContextObj::Scope_App);
        }

        $previousSpaceId = $contextObj->getContextVariable(BContextObj::Scope_CurrentNode, BContextObj::V_CurrentSpaceId);
        $spaceId = NULL;
        if (Blyn::app()->getActiveSpace() instanceof BSpace) {
            $spaceId = Blyn::app()->getActiveSpace()->getId();
        }

        if ($spaceId == NULL || $previousSpaceId != 'space_' . $spaceId) {
            $contextObj->resetContextVariable(BContextObj::Scope_Space);
        }
    }

    /**
     * 
     * @param type $data
     * @return BUIControl
     */
    public function getSenderControl($data = NULL) {
        if ($this->senderControl == NULL)
            $this->senderControl = $this->getCurrentScreen();
        return $this->senderControl;
    }

    /**
     * 
     * @param type $data
     * @return BUIControl
     */
    public function getUpdateControl($data = NULL) {
        if ($this->updateControl == NULL)
            $this->updateControl = $this->getCurrentScreen();
        return $this->updateControl;
    }

    public function onPrepare($data = NULL) {
        /*
          $linkId = $_REQUEST['b_linkId'];
          //set default update control and sender control
          $this->updateControl = $this;
          $this->senderControl = $this;
          //restore active nodes from last status
          BNode::restoreActiveNode();
          $contextData = Blyn::app()->getCurrentUser()->getContextVariable($linkId);
          if ($contextData != NULL) {
          $activeNodeData = $contextData['activeNode'];
          $senderControlData = $contextData['senderControl'];
          $this->senderControl = self::restoreFromArray($senderControlData);
          //reset activeNode from request
          BNode::restoreFromArray($activeNodeData);
          if (yii::app()->request->isAjaxRequest) {
          if ($contextData != NULL) {
          $updateControlData = $contextData['updateControl'];
          $this->updateControl = self::restoreFromArray($updateControlData);
          }
          }
          }
         */
    }

    /**
     * 
     * @param type $data
     * @return BUILink
     */
    public function getActiveLink($data = NULL) {
        return $this->activeLink;
    }

    public function setActiveLink($link) {
        if ($link instanceof BUILink)
            $this->activeLink = $link;
        if (is_string($link))
            $this->activeLink = new BUILink($link);
    }

    public function addActiveLinkData($data) {
        $activeLinkId = $this->getActiveLink()->getId();
        if (!isset($this->linkData[$activeLinkId])) {
            $this->linkData[$activeLinkId] = array();
        }
        if (is_array($data)) {
            $this->linkData[$activeLinkId] += $data;
        }
    }

    public function getLinkData($linkId) {
        if (isset($this->linkData[$linkId]))
            return $this->linkData[$linkId];
        return NULL;
    }

    public function getActiveLinkData($name, $data = NULL) {
        if (!empty($_GET) && isset($_GET[$name]))
            return $_GET[$name];
        if (!empty($_POST) && isset($_POST[$name]))
            return $_POST[$name];
        $linkData = Blyn::app()->getUIManager()->getLinkData($this->getActiveLink()->getId());
        if ($linkData != NULL && is_array($linkData)) {
            if (isset($linkData[$name]))
                return $linkData[$name];
        }
        //$data = yii::app()->session[$this->getId()];
        //if (isset($data[$name]))
        //return $data[$name];
        return NULL;
    }

}

?>
